package com.itlaobing.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import java.util.logging.Logger;

public final class JdbcUtils {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    String driverClassName;
    String url;
    String username;
    String password;
    
    private JdbcUtils(){
    }

    public static JdbcUtils getInstace(DatabaseType type){
        JdbcUtils instance = new JdbcUtils();

        switch ( type ) {
            case MYSQL :
                instance.driverClassName = "com.mysql.cj.jdbc.Driver";
                instance.url = "jdbc:mysql://localhost:3306/itlaobing?serverTimezone=Asia/Shanghai";
                instance.username = "root";
                instance.password = "";
                break ;
            case ORACLE :
                instance.driverClassName = "oracle.jdbc.driver.OracleDriver" ;
                instance.url = "jdbc:oracle:thin:@localhost:1521:T2081" ;
                instance.username = "itlaobing" ;
                instance.password = "itlaobing" ;
                break ;
        }

        return instance;
    }

    //负责加载驱动的方法
    public void load(){
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            logger.info( "驱动" + driverClassName + "加载失败" );
            e.printStackTrace();
        }
    }

    //负责 建立链接的方法
    public Connection connection(){
        try {
            return DriverManager.getConnection( url , username , password );
        } catch (SQLException throwables) {
            throw new RuntimeException( "数据库连接失败" , throwables );
        }
    }

    //负责 创建 Statement 实例
    public Statement statement(Connection connection){
        //判断
        if( Objects.isNull( connection ) ) {
            throw new NullPointerException( "你丫居然给我传个null" );
        }

        try {
            return connection.createStatement();
        } catch (SQLException ex) {
            throw new RuntimeException( "创建Statement失败" , ex );
        }
    }

    // 发送 SQL 给数据库 并获得返回结果

    // 关闭 释放资源
    public void release(Statement statement , Connection connection){
        if (Objects.nonNull(statement)) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (Objects.nonNull(connection)){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
